package com.oms.web.contronller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.oms.domain.User;
import com.oms.service.UserService;

/**
 * 用于上传操作的控制器
 * @author junfy
 *
 */
@Controller
public class FileUploadController {
	
	@Resource()
	UserService userService;


    @RequestMapping("/updateHeadPortrait")
    public String  updateHeadPortrait(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
        long  startTime=System.currentTimeMillis();	//开始上传文件的时间
        System.out.println("fileName："+file.getOriginalFilename());
        String path=request.getSession().getServletContext().getRealPath("/")+ 
        		"upload/image/user/user_head" +file.getOriginalFilename();	//头像文件存放的路径
        

        System.out.println(file.getOriginalFilename());
        System.out.println(file.getContentType());
         
        File newFile=new File(path);	//根据路径新建一个文件对象
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newFile);		//把上传的文件写入到新建的文件对象中
        long  endTime=System.currentTimeMillis();
        System.out.println("上传图片用的时间："+String.valueOf(endTime-startTime)+"ms");
        
        User user=(User) request.getSession().getAttribute("user");	//获取用户
        user.setHeadImageSrc("upload/image/user/user_head" +file.getOriginalFilename());
        userService.update(user);
        return "redirect:" +request.getHeader("Referer"); 
        
    }

 

}
